package cn.edu.sjtu.process_management.util;

import cn.edu.sjtu.process_management.exception.model.FileException;
import cn.edu.sjtu.process_management.constant.RespStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.stream.Collectors;

/**
 * @author loumoon
 * @date 2019-11-07 13:01
 */
@Component
public class StrConvertUtil {
    private static String charsetName; // 静态变量无法直接@Value注入值

    @Value("${charset.name}")
    public void setCharsetName(String charsetName) {
        StrConvertUtil.charsetName = charsetName;
    }

    /*MultipartFile转String*/
    public static String multiFileToStr(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            return new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining("\n"));
        } catch (Exception e) {
            throw new FileException(RespStatus.SERVER_ERROR);
        }
    }

    /*String转InputStream*/
    public static InputStream strToInStream(String str) {
        try {
            return new ByteArrayInputStream(str.getBytes(charsetName));
        } catch (Exception e) {
            throw new FileException(RespStatus.SERVER_ERROR);
        }
    }

}
